package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.financing.wap.dto.*;
import com.financing.wap.service.*;
import com.financing.wap.vo.OrderResultVO;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dao.IMessageDao;
import com.financing.wap.util.BasicUtils;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DateUtil;
import com.financing.wap.util.MessageUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.RandomUtils;
import com.financing.wap.util.SelectUtils;
import com.financing.wap.util.StringUtil;
import com.financing.wap.vo.OrderVO;
import com.financing.wap.vo.ProductProfitAndRebateVO;
import com.financing.wap.vo.QueryClientUserVo;
import com.financing.wap.vo.ShopperProductVO;
import com.financing.wap.web.controller.BaseController;

import cn.jpush.api.utils.Base64;

/**
 * @author lisu
 *	wap_jee_1.3 
 *	annualRevenue 预期收益Double 改成文本框 String 
 *	author lisu
 */
@Controller("apiOrderController")
@RequestMapping("/api/order")
public class OrderController extends BaseController  { 

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IProductOrderDataService  productOrderDataService ;

	@Autowired
	private IProductService productService;

	@Autowired
	private IClientService clientService;
	
	@Autowired
	private IAccountService accountService;
	
	@Autowired
	private IEmailTemplateService emailTemplateServiceImpl;
	
	@Autowired
	private IMessageDao messageDaoImpl;
	
	@Autowired
	private IFpFundInfoService fpFundInfoService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private MailSenderService mailSenderService;
	
	@Autowired
	public ISmsService smsService;
	
	@Autowired
	public IMessageService messageService;
	
	@Autowired
	private ISystemService systemService;
	
	@Autowired
	private IOrderTmpService orderTmpServiceImpl;
	
	@Autowired
	private IFpOrderPhoService fpOrderPhoService;

	@Autowired
	IFpShopperProductService fpShopperProductService;
	
	@Autowired
	private IRegisterService registerService;
	@Autowired
	private ISmsNewService smsNewService;
	@Autowired
	private IMessageJpushUserPhoneAliasService messageJpushUserPhoneAliasService;
	
	String oldOrderTime=PropertiesUtils.getValue("oldOrderTime");
	

	@Autowired
	private ICheckCodeService checkCodeServiceImpl;
	
	@Autowired
	private IYouDanAmountService youDanAmountServiceImpl;

	@Autowired
	private IFpFaUserContractService fpFaUserContractService;//合同service
	
	/**
	 * 展示所有订单列表
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		orderVo = queryVoChange(orderVo);
		if(StringUtils.isBlank(orderVo.getPayStatusStage()) || orderVo.getPayStatusStage().equals("1")){
			orderVo.setShopOrder("120");
		}
		
		result = userList(request,response,orderVo);

		return  result;
	}
	
	
	/**
	 * 取消预约
	 */
	@RequestMapping("/orderStatus")
	@ResponseBody
	public ResultMap orderStatus(HttpServletRequest request, HttpServletResponse response,String orderId,String updateType){
		Session session = SessionUtil.getSession();
		ResultMap result = new ResultMap();
		try{
			//参数空
			if(orderId == null || StringUtils.isBlank(updateType)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;

			}

			OrderDTO orderDto = orderService.getOrder(orderId);

			UserDTO loginUser = session.getUser();
			String userId = loginUser.getId();
			if(!orderDto.getFaid().equals(userId)){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违规操作，账号权限受限！");
				return result;
			}

			//rebateConfirm 320->330 确认返佣
			//cancel  110-> 999 提交预约-取消订单
			//delete 删除订单
			if("rebateConfirm".equals(updateType)){
				updateRebateConfirm(result,orderDto,userId);
			}else if("cancel".equals(updateType)){
				updateCancel(result, orderDto, userId);
			}else if("delete".equals(updateType)){
				updateDelete(result, orderDto, userId);
			}
		}catch(Exception e){
			log.error("query order orderStatus error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	private void updateRebateConfirm(ResultMap result, OrderDTO orderDto, String userId) throws Exception {
		if(Constants.STATUS_REBATE_GET.equals(orderDto.getPayStatus())){
			//当前状态是否为：返佣
			orderDto.setPayStatus(Constants.STATUS_REBATE_SURE);
			orderDto.setUpdateBy(userId.toString());
			orderService.changeOrderStatusRebateConfirm(orderDto);
			/**
			 * 这里在账户明细表中添加返佣入账详细记录
			 */
			//返佣额度
			//wao_jee_0.9: 返佣额度 改成 成交返佣额  （如果成交返佣额为空 就取 返佣额度 ）
			//BigDecimal rebateAmount = orderDto.getRebateAmount();
			BigDecimal rebateAmount;
			if(orderDto.getTransactionRebate() == null){
				rebateAmount = orderDto.getRebateAmount();
			}else{
				rebateAmount = orderDto.getTransactionRebate();
			}

			accountService.changeAccountByRebateConfirm(userId,rebateAmount);

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}else{
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
		}
	}
	private void updateCancel(ResultMap result, OrderDTO orderDto, String userId) {
		if(Constants.STATUS_PRE_NEW.equals(orderDto.getPayStatus())){
			//当前状态是否为：
			orderDto.setPayStatus(Constants.STATUS_CANCEL);
			orderDto.setUpdateBy(userId.toString());
			orderDto.setUpdateDate( new Date());
			orderService.changeOrderStatusPayConfirm(orderDto);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}else{
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
		}
	}

	private void updateDelete(ResultMap result, OrderDTO orderDto, String userId) {
		if(Constants.STATUS_CANCEL.equals(orderDto.getPayStatus()) || Constants.STATUS_CANCEL_140.equals(orderDto.getPayStatus()) || Constants.STATUS_CANCEL_888.equals(orderDto.getPayStatus())){
			//当前状态是否为：取消订单
			orderDto.setPayStatus(Constants.STATUS_CANCEL);
			orderDto.setDeleteTag("2");
			orderDto.setUpdateBy(userId.toString());
			orderDto.setUpdateDate( new Date());
			orderService.changeOrderStatus(orderDto);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}else{
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
		}
	}

	/**
	 * 订单各状态  数量
	 * @return
	 */
	@RequestMapping("/statusCount")
	@ResponseBody
	public ResultMap statusCount(HttpServletRequest request, HttpServletResponse response){
		Session session = SessionUtil.getSession();
		ResultMap result = new ResultMap();
		try{
			UserDTO loginUser = session.getUser();
			//当前登录人ID
			String faId = loginUser.getId();
			//订单状态-

			OrderVO orderVo = new OrderVO();
			orderVo.setFaid(faId);
			//获取   状态的数量
			Map<String, Integer> statusMap = getStatusMap(orderVo);

			result.setAttribute("statusMap", statusMap);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
		}catch(Exception e){
			log.error("query order statusCount error!",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	private Map<String, Integer> getStatusMap(OrderVO orderVo) {
		Map<String,Integer> statusMap =  new HashMap<String, Integer>();

		HashMap<String, String> map = Constants.orderCtrType_status;
		int allCount = 0;
		for (Map.Entry<String, String> entry : map.entrySet()) {
			orderVo.setPayStatusStage(entry.getKey());
			int statusCount = orderService.getOrderListCount(orderVo);
			allCount = allCount + statusCount;
			statusMap.put(entry.getKey(),statusCount);
		}

		statusMap.put("all",allCount);
		return statusMap;
	}
	/**
	 * 交易详情
	 * @return
	 */
	@RequestMapping("/{id}")
	@ResponseBody
	public ResultMap view(@PathVariable String id,HttpServletRequest request, HttpServletResponse response){ 
		ResultMap result = new ResultMap();

		try {
			OrderDTO orderDto = orderService.getOrder(id);
			if(orderDto==null){
				logger.info("==对象为查找到==");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				return result;
			}
			
			boolean checkResult = checkUserRight(request,response,orderDto.getFaid());
			if(!checkResult){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				result.setMessage("违规操作，账号权限错误！");
				return result;
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", orderDto);
			
		} catch (Exception e) {
			logger.error("order view error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}

	/**
	 * 返佣确认
	 * 订单id
	 * @return
	 */
	@RequestMapping("/rebateConfirm/{id}")
	@ResponseBody
	public ResultMap rebateConfirm(@PathVariable String id,HttpServletRequest request, HttpServletResponse response){ 
				
		ResultMap result = new ResultMap();
		OrderDTO orderDto = orderService.getOrder(id);
		
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String userId = loginUser.getId();
		if(!orderDto.getFaid().equals(userId)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，账号权限受限！");
			return result;
		}
		//320->330
		try {
			if(Constants.STATUS_REBATE_GET.equals(orderDto.getPayStatus())){
				//当前状态是否为：返佣
				orderDto.setPayStatus(Constants.STATUS_REBATE_SURE);
				orderDto.setUpdateBy(userId.toString());
				orderService.changeOrderStatusRebateConfirm(orderDto);
				/**
				 * 这里在账户明细表中添加返佣入账详细记录
				 */
				//返佣额度
				//wao_jee_0.9: 返佣额度 改成 成交返佣额  （如果成交返佣额为空 就取 返佣额度 ）
				//BigDecimal rebateAmount = orderDto.getRebateAmount();
				BigDecimal rebateAmount;
				if(orderDto.getTransactionRebate() == null){
					rebateAmount = orderDto.getRebateAmount();
				}else{
					rebateAmount = orderDto.getTransactionRebate();
				}
				
				accountService.changeAccountByRebateConfirm(userId,rebateAmount);
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			}

		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return  result;
	}
	/**
	 * 签单&打款
	 * 订单id
	 * @return
	 */
	@RequestMapping("/payConfirm/{id}")
	@ResponseBody
	public ResultMap payConfirm(@PathVariable String id,HttpServletRequest request, HttpServletResponse response){ 
		ResultMap result = new ResultMap();
		OrderDTO orderDto = orderService.getOrder(id);
		
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String userId = loginUser.getId();
		if(!orderDto.getFaid().equals(userId)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，账号权限受限！");
			return result;
		}
		//210->220
		try {
			if(Constants.STATUS_HETONG_BEGIN.equals(orderDto.getPayStatus())){
				//当前状态是否为：合同已寄出
				orderDto.setPayStatus(Constants.STATUS_HETONG_ORDER);
				orderDto.setUpdateBy(userId.toString());
				orderService.changeOrderStatusPayConfirm(orderDto);
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			}

		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return  result;

	}

	/**
	 * 变更状态为已经评论
	 * @return
	 */
	@RequestMapping("/comment/{id}")
	@ResponseBody
	public ResultMap comment(@PathVariable String id,HttpServletRequest request, HttpServletResponse response){ 
		ResultMap result = new ResultMap();
		OrderDTO orderDto = orderService.getOrder(id);
		
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String userId = loginUser.getId();
		if(!orderDto.getFaid().equals(userId)){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			result.setMessage("违规操作，账号权限受限！");
			return result;
		}
		//330->340
		try {
			if(Constants.STATUS_REBATE_SURE.equals(orderDto.getPayStatus())){
				//当前状态是否为：已确认返佣
				orderDto.setPayStatus(Constants.STATUS_REBATE_COMMENT);
				orderDto.setUpdateBy(userId.toString());
				orderService.changeOrderStatusPayConfirm(orderDto);
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			}else{
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
			}

		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return  result;

	}
	
	/**
	 * 申请预约
	 * @return
	 */
	@RequestMapping(value="/applyPre/{pid}",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap applyPreGet(@PathVariable int pid,HttpServletRequest request, HttpServletResponse response,OrderDTO orderDto){
		ResultMap result = new ResultMap();
		try {
			/**
			 * 判断是否经过FA认证
			 */

//			if(!hasFaAuthentication()){
//				result.setStatus(STATUS.ERROR);
//				result.setStatusCode(ResultMap.STATUS_CODE_AUTHENTICATION_ERROE);
//				
//				return result;
//			}
			
			
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			ProductDetailPageDTO productDetailPageDTO  = productService.getProductDetailView(pid);
		
			boolean check = checkProduct(request,response,productDetailPageDTO,loginUser);
			
			if(!check){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.ORDER_CODE_NOT_SALES_TIME);
				result.setMessage("预约产品有误！");
				return result;
			}
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("pid", pid);
			result.setAttribute("product", productDetailPageDTO);
			result.setAttribute("clientInfoJson", getClientInfo(faId));
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;		
	}

	
	
	
	
	/**
	 * 提交预约
	 * pid产品id，amount购买金额（百万）
	 * @return
	 */
	@RequestMapping(value="/applyPre",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap applyPrePost(HttpServletRequest request, HttpServletResponse response,OrderDTO orderDto){ 
		ResultMap result = new ResultMap();
		try {
//			if(!hasFaAuthentication()){ //判断是否经过FA认证
//				result.setStatus(STATUS.ERROR);
//				result.setStatusCode(ResultMap.STATUS_CODE_AUTHENTICATION_ERROE);
//				return result;
//			}
			//判断来源
			UserDTO loginUser = new UserDTO();
			if(StringUtils.isBlank(orderDto.getShopperId())){
				Session session = getSession(true);
				loginUser = session.getUser();
				orderDto.setShopperId(loginUser.getLoginName());
			}else{
				loginUser.setLoginName(orderDto.getShopperId());
				loginUser = userService.queryUserLoginName(loginUser);
			}
			String validatecode = request.getParameter("validatecode");
			String mobile = request.getParameter("mobile");
//			String loginName= loginUser.getLoginName();
			
			//检查数据是否为空
			if(StringUtils.isBlank(validatecode) && StringUtils.isBlank(orderDto.getShopperId())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//判断店铺产品上下架
//			FpShopperProductDTO shop=new FpShopperProductDTO();
//			shop.setProductState(1);  //默认为上架的
//			//查询产品code
//			shop.setUserId(loginUser.getId()); 
//			ProductDetailPageDTO c = productService.getProductDetailView(orderDto.getPid());
//			shop.setProductId(c.getProductCode());
//			
//			
//			List<ShopperProductVO> queryShopperProduct = fpShopperProductService.queryShopperProduct(shop,null);
//			if(queryShopperProduct.size()==0){
//				result.setStatus(STATUS.FAILE);
//				result.setStatusCode(ResultMap.PRODUCT_DOWN);
//				result.setMessage("产品已下架");
//				return result;
//			}
			
			if(!StringUtils.isBlank(validatecode)){
				//手机验证码
				if(checkCodeServiceImpl.CheckCodeSwitch()){
					Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
					//验证码超时
					if(checkOtpCodeTimeOut(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
						result.setStatus(ResultMap.STATUS.FAILE);
						result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
						result.setMessage("手机验证码超时！");
						return result;
						
					};
					ResultMap resultOtp = checkOtpCode(mobile,validatecode);
					if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
						result.setStatus(resultOtp.getStatus());
						result.setStatusCode(resultOtp.getStatusCode());
						result.setMessage(resultOtp.getMessage());
						return result;
					}
				}
			}
			//预约
			doOrderPre(request, response, orderDto, result, loginUser);
			
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("==>warn messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}
	
	/**
	 * 提交预约   妙点
	 * pid产品id，amount购买金额（百万）
	 * @return
	 */
	@RequestMapping(value="/applyPreMD")
	@ResponseBody
	public ResultMap applyPreMD(HttpServletRequest request, HttpServletResponse response,OrderDTO orderDto,RegisterDTO registerDto,HybxOrderDTO dto){ 
		ResultMap result = new ResultMap();
		try {
			String productType=request.getParameter("productType");
			if(!StringUtils.isBlank(dto.getFpHybxPhone())){//海外保险  判断注册
				registerDto.setMobile(dto.getFpHybxPhone());
			}
			//信托资管
			if(StringUtils.isBlank(productType)){
				logger.info("产品类型不对");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				return result;
			}
			if(StringUtils.isBlank(registerDto.getMobile())){
				logger.info("手机号不能为空");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				return result;
			}
			if(!StringUtil.isMobile(registerDto.getMobile())){
				logger.info("手机号不正确");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				return result;
			}
			if(StringUtils.isBlank(registerDto.getvCode())){
				logger.info("验证码不能为空");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				return result;
			}
			//校验验证码   测试环境开关是否开启，关闭不校验验证码
			if(checkCodeServiceImpl.CheckCodeSwitch()){
				Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
				//验证码超时
				if(checkOtpCodeTimeOut(registerDto.getMobile(),activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
					result.setStatus(ResultMap.STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
					result.setMessage("手机验证码超时！");
					return result;
					
				};
				ResultMap resultOtp = checkOtpCode(registerDto.getMobile(),registerDto.getvCode());
				if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
					result.setStatus(resultOtp.getStatus());
					result.setStatusCode(resultOtp.getStatusCode());
					result.setMessage(resultOtp.getMessage());
					return result;
				}
			}
			//TODO 需要进行事务控制
			//是否注册
			boolean mobileRegistered = userService.isMobileRegistered(registerDto.getMobile());
			UserDTO user=new UserDTO();
			if(!mobileRegistered){
				//自动注册
				String pwd="sfa"+RandomUtils.getRandomUtils(6);
				logger.debug(registerDto.getMobile()+"自动生成密码:"+pwd);
				registerDto.setPassword(pwd);
				//未注册 自动注册
				UserDTO userLogin=registerService.doRegister(registerDto);
				result.setAttribute("uImage", userLogin.getuImage());
				result.setAttribute("isNewUser", true);
				//TODO 发送用户给他密码短信  提出到xml中           
				String msgContent="恭喜您成功注册超级理财师（www.superfa.cn），用户名:【"+registerDto.getMobile()+"】,密码:【"+pwd+"】，如有疑问请电询400-855-8085。";
				logger.info(msgContent);
				try {
					smsService.sendOtpMessage(registerDto.getMobile(),msgContent,Constants.regPasswdSmsAd);
				} catch (Exception e) {
					logger.error("send regpasswdsmsadd error",e);
				}
				user=userLogin;
			}else{
				user.setLoginName(registerDto.getMobile());
				//查询用户信息
				user = userService.queryUserByMobile(user);
			}
			
			//自动登录  存储  session
			autoLogin(request, user);
			
			result.setAttribute("id", user.getId());
			logger.info("userId"+user.getId()+"==="+user.getLoginName()+"==="+user.getMobile());
			
			if("xtzg".equals(productType)){
				logger.info("产品类型 xtzg");
				//预约
				doOrderPre(request, response, orderDto, result, user);
			}else if("hwbx".equals(productType)){
				logger.info("产品类型 hwbx");
				//海外保险下单
				dohwbxOrder(dto, request, result, user);
			}
		} catch (Exception e) {
			logger.error("==>warn messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}
	/**
	 * 
	
	* @Title: doOrderPre
	
	* @Description: 预约订单  信托资管
	
	* @param @param request
	* @param @param response
	* @param @param orderDto
	* @param @param result
	* @param @param loginUser
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	public ResultMap doOrderPre(HttpServletRequest request,
			HttpServletResponse response, OrderDTO orderDto, ResultMap result,
			UserDTO loginUser) {
		//机构不能预约产品
		String uType = loginUser.getUType();
		if(Constants.FA_TYPE_CORP.equals(uType)){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.ORDER_ORG_NOT_APPLY);
			result.setMessage("机构不能预约！");
			return result;
		}
		logger.info("======获取项目详情========");
		//获取产品（销售、核心、成本）
		ProductDetailPageDTO productDetailPageDTO  = productService.getProductDetailViewByprice(orderDto.getPid());
		
		logger.info("view product end!!");
		//判断产品是否可以预约,如果状态不在募集中或者预售中就 不可预约
		if(productDetailPageDTO!=null && StringUtils.isNotBlank(productDetailPageDTO.getSaleStatus())){
			String saleStatus = productDetailPageDTO.getSaleStatus();
			if("01".equals(saleStatus) || "04".equals(saleStatus) || "05".equals(saleStatus)){
				logger.info("this saleStatus  not equals '02' or '03' ");
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.SALE_STATUS_BUKEYUYUE_FAILE);
				return result;
			}
		}
		
		orderDto.setpName(productDetailPageDTO.getProductShortName());
		orderDto.setPid(productDetailPageDTO.getProductId());
		
		//判断订单金额是否合法
		if(!isTureOrderAmount(productDetailPageDTO,orderDto,result)){
			return result;
		}
		//订单编号
		String orderCode  = createOrderCode();
		
		if(StringUtils.isEmpty(orderCode)){
			logger.info("====>order code is null<====");
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.ORDER_CODE_CREATE_ERROR);
			return result;
		}
		orderDto.setOrderCode(orderCode);
		//用于消息显示
		String messageAmount = orderDto.getAmount().toString();
		BigDecimal buyAmount = orderDto.getAmount().multiply(new BigDecimal(10000));
		String faId = loginUser.getId();

		String clientIdStr = request.getParameter("clientId");
		ClientUserBaseDTO clientDTO = null;
		Integer clientId = null;
		logger.info("search Client user start!!");
		if(StringUtils.isNotBlank(clientIdStr)){
			clientId = Integer.valueOf(clientIdStr);
			clientDTO = clientService.searchClientUserBaseById(clientId);
		}else{
			String name = request.getParameter("name");
			String mobile = request.getParameter("mobile");
			ClientUserBaseDTO checkDTO = clientReNameCheck(faId,name,mobile);
			if(checkDTO!=null){
				logger.info("fount rename clientInfo！");
				clientId = checkDTO.getId();
			}else{
				logger.info("create clientInfo！");
				clientDTO = new ClientUserBaseDTO();
				if(StringUtils.isBlank(name)){
					name = "未知";
				}if(StringUtils.isBlank(mobile)){
					mobile = "未知";
				}
				clientDTO.setcName(name);
				clientDTO.setcMobile(mobile);
				clientDTO.setcPaCode(faId.toString());
				clientDTO.setCreateBy(faId.toString());
				clientDTO.setUpdateBy(faId.toString());
				clientId = clientService.insertClientUserBase(clientDTO); //添加预约人信息
			}
			
		}
		
		logger.info("提交预约前，开始检查产品的合法性");
		
		boolean check = checkProduct(request,response,productDetailPageDTO,loginUser);
		if(!check){
			result.setStatus(STATUS.FAILE);
			result.setStatusCode(ResultMap.ORDER_CODE_NOT_SALES_TIME);
			result.setMessage("预约产品有误！");
			return result;
		}
		
		//将页面内容，万元转为元
		orderDto.setAmount(buyAmount);
		//交易额的
		BigDecimal amount = orderDto.getAmount();
		//计算返佣
		
		
		if(!Constants.FP_CORP_TYPE_PRIVATE.equals(productDetailPageDTO.getCorpType())){
			orderDto = getCurrentRebateAmountInfo(productDetailPageDTO,amount,orderDto);
		}
		orderDto.setoMediaSource(StringUtil.isNullOrEmptyStr((String) SessionUtil
				.getSession().getAttribute("mid")) ? Constants.MEDIA_SOURCE_PT
						: (String) SessionUtil.getSession().getAttribute("mid"));
		orderDto.setClientid(clientId);
		orderDto.setFaid(loginUser.getId());
		orderDto.setCreateBy(String.valueOf(loginUser.getId()));
		orderDto.setUpdateBy(String.valueOf(loginUser.getId()));
		if(orderDto.getRebateAmount()!=null&&orderDto.getRebateAmount().intValue()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_NOT_IN_RANGE);
			result.setMessage("未找到返佣区间");
			return result;
		}
		logger.info("==>applyPreOrder start!!");
		orderDto.setFaName( loginUser.getLoginName());
		// 查看是否是有单模式订单
		orderDto = orderService.preYouDanOrder(orderDto);
		String id = orderService.applyPreOrder(orderDto);
		
		result.setStatus(STATUS.SUCCESS);
		result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		result.setAttribute("orderId", id);
		//发送邮件和短信通知
		Map<String,Object> params = new HashMap<String,Object>();
		String mobile = request.getParameter("mobile");
		if(StringUtils.isNotBlank(mobile)){
			params.put("uName", mobile);
		}else{
			params.put("uName", loginUser.getLoginName());
		}
		
		params.put("time", DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		params.put("orderNo", orderDto.getOrderCode());
		params.put("productId", orderDto.getPid().toString());
		params.put("productShourName", productDetailPageDTO.getProductShortName());
		params.put("orderAmount", messageAmount);
//			sendMessageAndMailTOWorker(params,"messageAndMail","applyOrderWork");
		params.put("mailUrl", loginUser.getuEmail());
		params.put("otpMobile", loginUser.getLoginName());
		
		params.put("shopperId", orderDto.getShopperId());
		//applyOrder
		sendMessageAndMailTOFA(params,"messageAndMail","applyOrderWorkShop",Constants.ClientOrderSendSms);
		
		//添加推送
		try {
			
			// 根据用户查询出绑定的设备标示
			MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
			dto.setFpUserId(loginUser.getId());
			MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
			if(null != phoneAlias ){
	//			logger.info("goto url shopId: "+shopId);
				MessageJpushDTO messageJpushDTO = new MessageJpushDTO();
	
				messageJpushDTO.setFpJpushMsgRec(phoneAlias.getFpJpushAliasShop());
				messageJpushDTO.setFpJpushTitle("金策师预约");
				
				String contentJpush = "【%s】，客户姓名【%s】，金额【%s】万，手机号码【%s】请及时处理";
				contentJpush=String.format(contentJpush, productDetailPageDTO.getProductShortName(),request.getParameter("name"), messageAmount, request.getParameter("mobile"));
//				messageJpushDTO.setFpJpushContent("您的店铺有新的预约单，请及时跟进处理");
				messageJpushDTO.setFpJpushContent(contentJpush);
//				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(PropertiesUtils.getValue("jiGuangPushRedrictShopVisit").getBytes())));
				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(PropertiesUtils.getValue("jiGuangPushRedrictShopOrder").getBytes())));
//				messageJpushDTO.setFpJpushMsgType("05");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushMsgType("03");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
				messageJpushDTO.setCreateBy("");
				messageJpushDTO.setCreateDate(new Date());
				messageJpushDTO.setUpdateBy("");
				messageJpushDTO.setFpJpushShopType("1");  //0 客户,1 订单
				messageJpushDTO.setUpdateDate(new Date());
				messageJpushDTO.setFpJpushSource("shop"); //加店铺标识
				messageJpushUserPhoneAliasService.addJpushMessage(messageJpushDTO);
			}
		}catch(Exception e) {
			logger.error("goto error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		
		return result;

	}
	
	// 发送短信给FA
	private void sendMessageAndMailTOFA(Map<String,Object> params,String type,String code,String smsType){
		
		Map<String,Object> m  = MessageUtil.getMessage(type,code,params);
		String content = (String)m.get(MessageUtil.KEY_CONTENT);
//		content = content+systemService.getSmsAdContent(smsType);
		//邮件发送
//		if(params.get("mailUrl")!=null){
//			MessageMailDTO messageMailDTO = new MessageMailDTO();
//			Map<String,Object> param = new HashMap<String,Object>();
//			param.put("uName", params.get("uName"));
//			param.put("pOrderNum", params.get("orderNo"));
//			param.put("PName", params.get("productShourName"));
//			param.put("pAmount", params.get("orderAmount"));
//			param.put("pDueTime", params.get("time"));
//			param.put("pid", params.get("productId"));
//			param = emailTemplateServiceImpl.spliceEmailContent(Constants.mail_template_order_apply_per, param);
//			
//			messageMailDTO.setFpMailContent((String)param.get(Constants.mail_content));
//			messageMailDTO.setFpMailTitle((String)param.get(Constants.mail_subject));
//			messageMailDTO.setFpMailType(Constants.mail_order_apply_per_FA);
//			messageMailDTO.setFpMailSendType(Constants.message_type_now);
//			messageMailDTO.setFpMailSendTimes(new Integer(0));
//			messageMailDTO.setFpMailTo((String)params.get("mailUrl"));
//			messageMailDTO.setStatus(Constants.status_normal);
//			messageMailDTO.setFpMailSendStatus(Constants.message_status_not_send);
//			messageMailDTO.setCreateBy((String)params.get("uName"));
//			messageMailDTO.setUpdateBy((String)params.get("uName"));
//			messageMailDTO.setCreateDate(new Date());
//			messageMailDTO.setUpdateDate(new Date());
//			
////			messageService.insertMailInfo(messageMailDTO);
//		}
//		
//		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
//		messageSmsDTO.setFpSmsContent(content);
//		messageSmsDTO.setFpSmsType(Constants.orderApplySmsAd);
//		messageSmsDTO.setFpSmsSendType(Constants.message_type_now);
//		messageSmsDTO.setFpSmsRecivePhoneNo((String)params.get("otpMobile"));
//		messageService.addMessageSms(messageSmsDTO); 
		
		//走店铺订单短信
		String shopperId=params.get("shopperId").toString();
		List mobileList=new ArrayList<String>();
		mobileList.add(shopperId);
		smsNewService.sendSms(mobileList,content,smsType);
		
	}

	/**
	 * 
	* @Title: isTureOrderAmount 
	* @Description: 判断是否为合法的订单金额，订单金额=产品起购金额+n*累进金额  (n为大于等于的整数) 且订单金额应该不大预售金额-已经实际销售金额
	* @param @return    
	* @return boolean   
	* @throws
	 */
	private boolean isTureOrderAmount(ProductDetailPageDTO productDetailPageDTO,OrderDTO orderDTO,ResultMap result){
		
		//订单金额
		BigDecimal orderAmount = orderDTO.getAmount().multiply(new BigDecimal(10000));
		//产品起购金额
		BigDecimal minimumAmount = productDetailPageDTO.getMinimumAmount();
		//产品实际销售金额
		BigDecimal signingAmount = productDetailPageDTO.getSigningAmount();
		//产品预售金额
		BigDecimal expectSaleAmount = productDetailPageDTO.getExpectSaleAmount();
		//产品累进金额
		BigDecimal progressiveAmount = productDetailPageDTO.getpProgressiveAmount();
		//产品本期规模
		BigDecimal issuingScale = productDetailPageDTO.getIssuingScale();
		//产品已经销售总额
		BigDecimal allSubscriptionAmount = productDetailPageDTO.getAllSubscriptionAmount();
		
		log.info("orderAmount:"+orderAmount);
		log.info("minimumAmount:"+minimumAmount);
		log.info("signingAmount:"+signingAmount);
		log.info("expectSaleAmount:"+expectSaleAmount);
		log.info("progressiveAmount:"+progressiveAmount);
		log.info("issuingScale:"+issuingScale);
		log.info("allSubscriptionAmount:"+allSubscriptionAmount);
		//订单金额减去起购金额的值
		BigDecimal multiple = orderAmount.subtract(minimumAmount);
		
		//比起购金额还小
		if(multiple.signum()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_MIN_ERROR);
			result.setMessage("购买额低于起拍金额，起拍额为:"+minimumAmount);
			return false;
		}
		
		//不是累进金额的倍数
		if(multiple.remainder(progressiveAmount).compareTo(new BigDecimal(0)) != 0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_PROGRESSIVE_ERROR);
			result.setMessage("累进购买金额有误。");
			return false;
		}

		//改成本期规模-本期已销售金额
		/*BigDecimal moreAount =  expectSaleAmount.subtract(signingAmount);
		//订单金额超过可预售金额
		if((moreAount.subtract(orderAmount)).signum()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_MAX_ERROR);
			result.setMessage("可预订金额为:"+moreAount);
			return false;
		}*/

		BigDecimal moreAount =  issuingScale.subtract(allSubscriptionAmount);
		//订单金额超过可预售金额
		if((moreAount.subtract(orderAmount)).signum()<0){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_MAX_ERROR);
			result.setMessage("可预订金额为:"+moreAount);
			return false;
		}


		
		return  true;
	}
	

	/**
	 * 获取Fa的客户信息forJson
	 * @param faId
	 * @return
	 */
	private List<Map<String,Object>> getClientInfo(String faId){
		QueryClientUserVo queryVo = new QueryClientUserVo();
		queryVo.setFaId(faId);
		List<ClientUserBaseDTO> clientList  = clientService.getClientUserList(queryVo);
		Map<String,Object> clientInfoMap = null;
		List<Map<String,Object>> listForJson = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> selectSex = SelectUtils.getSelectSex();
		String sexLabel="";
		for(ClientUserBaseDTO c:clientList){
			for(Map<String,Object> sexMap:selectSex){
				if(sexMap.get(SelectUtils.MAP_KEY).equals(c.getcSex())){
					sexLabel = (String)sexMap.get(SelectUtils.MAP_VALUE);
					break;
				}
			}
			clientInfoMap = new HashMap<String,Object>();
			clientInfoMap.put("id", c.getId());
			clientInfoMap.put("name", c.getcName());
			clientInfoMap.put("sex", sexLabel);
			clientInfoMap.put("tel", c.getcMobile());
			listForJson.add(clientInfoMap);
		}
		return listForJson;
	}

	/**
	 * 根据交易额度决定返佣比率及额度
	 * @return
	 */
	private OrderDTO getCurrentRebateAmountInfo(ProductDetailPageDTO productDetailPageDTO,BigDecimal amount,OrderDTO orderDto){
		List<ProductProfitAndRebateVO> list = productDetailPageDTO.getProfitAndRebateList();
		BigDecimal expectSaleAmount = productDetailPageDTO.getExpectSaleAmount();
		
		 //	wap_jee_1.3 
		 // 		annualRevenue 预期收益Double 改成文本框 String 
		 // 	 	author lisu
		//预期年化收益
		String annualRevenue =  productDetailPageDTO.getAnnualRevenueExpect();
		
		BigDecimal rebateAmount = new BigDecimal(-1);
		BigDecimal common = new BigDecimal(0.01);
		BigDecimal sellingRebate = new BigDecimal(-1);
		BigDecimal costRebate  = new BigDecimal(-1);
		BigDecimal coreRebate  = new BigDecimal(-1);
		BigDecimal backRebateAmount = new BigDecimal(-1);
		BigDecimal backSellingRebate = new BigDecimal(-1);
		BigDecimal backCostRebate  = new BigDecimal(-1);
		BigDecimal backCoreRebate  = new BigDecimal(-1);
		
		BigDecimal max = new BigDecimal(-1);
		Double rebateMax = null; 
		BigDecimal sellingPriceMax = new BigDecimal(-1);
		BigDecimal costPriceMax = new BigDecimal(-1);
		BigDecimal corePriceMax = new BigDecimal(-1);
		Double backRebateMax = null; 
		BigDecimal backSellingPriceMax = new BigDecimal(-1);
		BigDecimal backCostPriceMax = new BigDecimal(-1);
		BigDecimal backCorePriceMax = new BigDecimal(-1);
		for(ProductProfitAndRebateVO vo:list){
			if(vo.getEndAmount().compareTo(max) > 0){
				max = vo.getEndAmount();
				rebateMax = vo.getRebate();
				sellingPriceMax = vo.getSellingPrice();
				costPriceMax = vo.getCostPrice();
				corePriceMax = vo.getCorePrice();
				backRebateMax = vo.getBackRabate();
				backSellingPriceMax = vo.getBackSellingPrice();
				backCostPriceMax = vo.getCostBackPrice();
				backCorePriceMax = vo.getCoreBackPrice();
			}
		}
		
		log.info("max rebate amount is "+max);
		log.info("max rebate is "+ rebateMax);
		
		for(ProductProfitAndRebateVO vo:list){
			//起始金额
			BigDecimal start =vo.getStartAmount();
			//结束金额
			BigDecimal end = vo.getEndAmount();
			//返佣 挂网价
			Double rebate = vo.getRebate();
			//销售价
			BigDecimal  sellingPrice = vo.getSellingPrice();
			//核心价
			BigDecimal  corePrice = vo.getCorePrice();
			//成本价
			BigDecimal  costPrice = vo.getCostPrice();
			// ————订单流程改造 后端价格
			// 后端 返佣 挂网价
			Double backRebate = vo.getBackRabate();
			// 后端 销售价
			BigDecimal  backSellingPrice = vo.getBackSellingPrice();
			// 后端 核心价
			BigDecimal  backCorePrice = vo.getCoreBackPrice();
			// 后端 成本价
			BigDecimal  backCostPrice = vo.getCostBackPrice();
			// 是否协议，0：否，1是
			String isAgreement = vo.getpIsAgreement();
			
			if(amount.intValue() >= max.intValue() && amount.intValue()<=expectSaleAmount.intValue()){
				//最大边界值
				if(!vo.getRebateIsRatio()){
					logger.info("=====进入最大边界值的固定值=====");
					rebateAmount= BigDecimal.valueOf(rebateMax);
					orderDto.setRebateRate(Constants.ORDER_REBATE_AMOUNT);
					backRebateAmount = BigDecimal.valueOf(backRebateMax);
					orderDto.setBackRebateRate(Constants.ORDER_REBATE_AMOUNT);
					// 返佣ID
					orderDto.setAnnualRrevenueId(vo.getId());
				}else{
					rebateAmount = BigDecimal.valueOf(rebateMax*0.01).multiply(amount);
					orderDto.setRebateRate(BigDecimal.valueOf(rebateMax));
					backRebateAmount = BigDecimal.valueOf(backRebateMax*0.01).multiply(amount);
					orderDto.setBackRebateRate(BigDecimal.valueOf(backRebateMax));
					// 返佣ID
					orderDto.setAnnualRrevenueId(vo.getId());
				}
				sellingRebate = sellingPriceMax==null?null:sellingPriceMax.multiply(common).multiply(amount);//销售返佣额
				coreRebate = corePriceMax==null?null:corePriceMax.multiply(common).multiply(amount);//核心返佣额
				costRebate = costPriceMax==null?null:costPriceMax.multiply(common).multiply(amount);//成本返佣额
				backSellingRebate = sellingPriceMax==null?null:backSellingPriceMax.multiply(common).multiply(amount);//后端销售返佣额
				backCoreRebate = corePriceMax==null?null:backCorePriceMax.multiply(common).multiply(amount);//后端核心返佣额
				backCostRebate = costPriceMax==null?null:backCostPriceMax.multiply(common).multiply(amount);//后端成本返佣额
				
				orderDto.setSellingPrice(sellingPriceMax);
				orderDto.setCorePrice(corePriceMax);
				orderDto.setCostPrice(costPriceMax);
				orderDto.setBackSellingPrice(backSellingPriceMax);
				orderDto.setBackCorePrice(backCorePriceMax);
				orderDto.setBackCostPrice(backCostPriceMax);
				
				orderDto.setRebateAmount(rebateAmount);
				orderDto.setSellingRebate(sellingRebate);
				orderDto.setCoreRebate(coreRebate);
				orderDto.setCostRebate(costRebate);
				orderDto.setBackRebateAmount(backRebateAmount);
				orderDto.setBackSellingRebate(backSellingRebate);
				orderDto.setBackCoreRebate(backCoreRebate);
				orderDto.setBackCostRebate(backCostRebate);
				orderDto.setAnnualRevenue(annualRevenue);
				return orderDto;
			}
			//判断预约金额是否在此区间
			if(start.intValue()<=amount.intValue()&&amount.intValue()<end.intValue()){
				if(!vo.getRebateIsRatio()){
					logger.info("=====进入固定值=====");
					rebateAmount= BigDecimal.valueOf(rebate);
					orderDto.setRebateRate(Constants.ORDER_REBATE_AMOUNT);
					backRebateAmount= BigDecimal.valueOf(backRebate);
					orderDto.setBackRebateRate(Constants.ORDER_REBATE_AMOUNT);
					// 返佣ID
					orderDto.setAnnualRrevenueId(vo.getId());
				}else{
					rebateAmount = BigDecimal.valueOf(rebate*0.01).multiply(amount);
					orderDto.setRebateRate(BigDecimal.valueOf(rebate));
					backRebateAmount = BigDecimal.valueOf(backRebate*0.01).multiply(amount);
					orderDto.setBackRebateRate(BigDecimal.valueOf(backRebate));
					// 返佣ID
					orderDto.setAnnualRrevenueId(vo.getId());
				}
				//计算  销售返佣额| 核心返佣额| 成本返佣额
				sellingRebate = sellingPrice == null?null:sellingPrice.multiply(common).multiply(amount);//销售返佣额
				coreRebate = corePrice == null?null:corePrice.multiply(common).multiply(amount);//核心返佣额
				costRebate = costPrice == null?null:costPrice.multiply(common).multiply(amount);//成本返佣额
				backSellingRebate = backSellingPrice == null?null:backSellingPrice.multiply(common).multiply(amount);//后端销售返佣额
				backCoreRebate = backCorePrice == null?null:backCorePrice.multiply(common).multiply(amount);//后端核心返佣额
				backCostRebate = backCostPrice == null?null:backCostPrice.multiply(common).multiply(amount);//后端成本返佣额
				
				orderDto.setSellingPrice(sellingPrice);
				orderDto.setCorePrice(corePrice);
				orderDto.setCostPrice(costPrice);
				orderDto.setBackSellingPrice(backSellingPrice);
				orderDto.setBackCorePrice(backCorePrice);
				orderDto.setBackCostPrice(backCostPrice);
				
				orderDto.setRebateAmount(rebateAmount);
				orderDto.setSellingRebate(sellingRebate);
				orderDto.setCoreRebate(coreRebate);
				orderDto.setCostRebate(costRebate);
				orderDto.setBackRebateAmount(backRebateAmount);
				orderDto.setBackSellingRebate(backSellingRebate);
				orderDto.setBackCoreRebate(backCoreRebate);
				orderDto.setBackCostRebate(backCostRebate);
				orderDto.setIsAgreement(isAgreement);
//				orderDto.setRebateAmount(rebateAmount);
				orderDto.setAnnualRevenue(annualRevenue);
				return orderDto;
			}
		}
		return orderDto;
	}
	
	/**
	 * 个人用户订单列表
	 * @param request
	 * @param response
	 * @param orderVo
	 * @return
	 */
	private  ResultMap userList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			//自己店铺标识
			orderVo.setShopperId(loginUser.getLoginName());
			orderVo.setFaid(faId);
			Pager pager = new Pager();
			
			Integer count = orderService.getOrderListCount(orderVo);
			pager.setTotalCount(count);
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());

			//排序方式，将参数转化成数据库参数
			getOrderOrderType(orderVo);

			List<OrderDTO> orderDtoList = orderService.getOrderList(orderVo);
			List<OrderResultVO> orderResultVoList = new ArrayList<OrderResultVO>();

			for (OrderDTO  orderDTO:orderDtoList) {
				
				OrderResultVO orderResultVO = new OrderResultVO();
				

				//将信息转化成前台信息
				getOrderResult(orderDTO, orderResultVO);

				//获取BIZ状态
				getBizStatus(orderDTO, orderResultVO);

				//获取上传状态
				getFlagUploadForOrderId(orderDTO, orderResultVO);

				//获取 三件套 状态 （01:未提交审核 02提交审核  未审核  03:提交审核 审核成功  04:提交审核 审核失败）
				getPhoStatusForOrderId(orderDTO,orderResultVO);

				//获取合同 状态 "01"; //待申请 "02"; //已申请 "03"; //已寄出 "04"; //已回收
				getContractStatusForOrderId(orderDTO, orderResultVO);

				//获取订单佣金
				getOrderCostCount(orderDTO,orderResultVO);

				orderResultVoList.add(orderResultVO);
			}


			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", orderResultVoList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.error("error  order userList:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	private void getOrderResult(OrderDTO orderDTO, OrderResultVO orderResultVO) {
		orderResultVO.setAmount(orderDTO.getAmount());
		orderResultVO.setcName(orderDTO.getcName());
		//System.out.println(orderDTO.getcMobile()+"===========");
		orderResultVO.setcMobile(orderDTO.getcMobile());
		orderResultVO.setId(orderDTO.getId());
		orderResultVO.setOrderCode(orderDTO.getOrderCode());
		orderResultVO.setPayStatus(orderDTO.getPayStatus().toString());
		orderResultVO.setPayStatusStage(Constants.order_status_str.get(orderDTO.getPayStatus().toString()));
		orderResultVO.setCreateDate(DateUtil.formatDate(orderDTO.getCreateDate(),"yyyy-MM-dd"));
		orderResultVO.setPid(orderDTO.getPid());
		orderResultVO.setpName(orderDTO.getpName());
		orderResultVO.setpCode(orderDTO.getpCode());
		orderResultVO.setpType(orderDTO.getpType());
		orderResultVO.setRebateAmount(orderDTO.getTransactionRebate());
	}

	private void getBizStatus(OrderDTO orderDTO, OrderResultVO orderResultVO) {
		String yyz = Constants.orderCtrType_status.get("1");
		String ddsb = Constants.orderCtrType_status.get("5");
		if(yyz.indexOf(orderDTO.getPayStatus().toString()) >= 0){
			orderResultVO.setIsCancel(true);
		}else if(ddsb.indexOf(orderDTO.getPayStatus().toString()) < 0){
			orderResultVO.setIsPho(true);
			orderResultVO.setIsContract(true);
		}
		if(orderDTO.getPayStatus() == 320 || orderDTO.getPayStatus() == 321){
			orderResultVO.setIsRebateConfirm(true);
		}
	}
	private void getContractStatusForOrderId(OrderDTO orderDTO, OrderResultVO orderResultVO) throws SQLException {
		FpFaUserContractDTO fpFaUserContract = new FpFaUserContractDTO();
		fpFaUserContract.setOrderId(orderDTO.getId());
		fpFaUserContract = fpFaUserContractService.queryListGetFirst(fpFaUserContract);

		if(fpFaUserContract != null && StringUtils.isNotBlank(fpFaUserContract.getContractStatus())){
			orderResultVO.setContractStatus(fpFaUserContract.getContractStatus());
			orderResultVO.setContractCode(fpFaUserContract.getContractCode());
			orderResultVO.setUserContract(fpFaUserContract);
		}

		if(StringUtils.isBlank(orderResultVO.getContractStatus())){
			orderResultVO.setContractStatus(Constants.UserContractDTO.STATUS_CONTRACT_01);
		}
	}
	private void getFlagUploadForOrderId(OrderDTO orderDTO, OrderResultVO orderResultVO) {
		try {
			if(DateUtil.format(oldOrderTime, "yyyy-MM-dd").before(orderDTO.getCreateDate())){
				orderResultVO.setFlagUpload(true);
			}else{
				orderResultVO.setFlagUpload(false);
			}
		} catch (Exception e) {
			orderResultVO.setFlagUpload(false);
			log.error("format oldOrderTime",e);
		}
	}

	//获取 三件套 状态
	private void getPhoStatusForOrderId(OrderDTO orderDTO,OrderResultVO orderResultVO) {

		FpOrderPhoDTO fpd=new FpOrderPhoDTO();
		fpd.setoId(orderDTO.getId());
		List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);

		String phoStatus = Constants.order_data_pho_rev_no;
		Map<String,String> map = new HashMap<String,String>();
		for(FpOrderPhoDTO PODtmp  : PODList){
			if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
				map.put("01", "01");
				continue;
			}
			map.put(PODtmp.getoPhoStatus(), "01");
		}

		if(map.containsKey(Constants.order_data_pho_rev_no)){
			phoStatus = Constants.order_data_pho_rev_no;
			orderResultVO.setPhoStatus(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_fail)){
			phoStatus = Constants.order_data_pho_rev_fail;
			orderResultVO.setPhoStatus(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_yes) ){
			phoStatus = Constants.order_data_pho_rev_yes;
			orderResultVO.setPhoStatus(phoStatus);
		}else if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
			phoStatus = Constants.order_data_pho_rev_success;
			orderResultVO.setPhoStatus(phoStatus);
		}else{
			//默认
			orderResultVO.setPhoStatus(phoStatus);
		}
	}
	private void getOrderCostCount(OrderDTO orderDTO,OrderResultVO orderResultVO) {
		if(Constants.orderCtrType_status.get("1").indexOf(orderDTO.getPayStatus().toString()) >= 0  || Constants.orderCtrType_status.get("5").indexOf(orderDTO.getPayStatus().toString()) >= 0){
			orderResultVO.setRebateAmount(null);
			return ;
		}
		FpOrderCostDTO orderCost = new FpOrderCostDTO();
		orderCost.setOrderId(orderDTO.getId());
		orderCost.setCostType("\""+ Constants.OrderCostDTO.STATUS_QD_CWJY+"\"");
		orderCost.setDeleteTag("1");
		BigDecimal c = orderService.queryOrderCostCount(orderCost);

		if(c != null && c.compareTo(BigDecimal.ZERO) == 1){
			orderResultVO.setRebateAmount(c);
		}
	}
	/**
	 * 机构订单列表
	 * @param request
	 * @param response
	 * @param orderVo
	 * @return
	 */
	private  ResultMap corpList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String corpId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			orderVo.setFaid(corpId);
			Pager pager = new Pager();
					
			//查询出，所拥有的理财师列表
			List<Integer> intList =  orderService.getSonFaidList(corpId);
			if(intList == null || intList.size()<=0){
				pager.setTotalCount(0);
				pager.setPageSize(orderVo.getPageSize());
				pager.setPageNo(Integer.parseInt(pageNo));
				result.setAttribute("list", Collections.EMPTY_LIST);
				result.setAttribute("pager", pager);
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				return result;
			}
			orderVo.setSonFaidList(intList);
			Integer count = orderService.getCorpOrderListCount(orderVo);
			pager.setTotalCount(count);
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());

			List<OrderDTO> orderDtoList = orderService.getCorpOrderList(orderVo);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", orderDtoList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.error("corp orderList error:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	
	
	/**
	 * 客户重名验证
	 * @param faId
	 * @param cName
	 * @param cMobile
	 * @return
	 */
	private ClientUserBaseDTO clientReNameCheck(String faId,String cName,String cMobile){
		QueryClientUserVo queryVo = new QueryClientUserVo();
		queryVo.setFaId(faId);
		queryVo.setcName(cName);
		queryVo.setcMobile(cMobile);
		List<ClientUserBaseDTO> list = clientService.getClientUserList(queryVo);
		if(list.size()>0){
			return list.get(0);
		}
			return null;
		
	}
	
	
	private  boolean checkProduct(HttpServletRequest request, HttpServletResponse response,ProductDetailPageDTO productDetailPageDTO,UserDTO loginUser){
//		Session session = getSession(true);
//		UserDTO loginUser = session.getUser();
		String uType = loginUser.getUType();
//		Integer userId = loginUser.getId();
		if(Constants.FA_TYPE_CORP.equals(uType)){
			return false;
		}
		//对预约条件进行判断
		Date currentDate = new Date();
/*		if(productDetailPageDTO ==null || productDetailPageDTO.getEstablishmentTime()!=null || currentDate.before(productDetailPageDTO.getSaleDateStart()) || (null!=productDetailPageDTO.getSaleDateEnd()&&currentDate.after(productDetailPageDTO.getSaleDateEnd()))){
			//不再销售期内，不允许预约
			logger.info("sale date is error !!");
			return false;
		}*/
		
		if(productDetailPageDTO ==null || productDetailPageDTO.getEstablishmentTime()!=null ||  (null!=productDetailPageDTO.getSaleDateEnd()&&currentDate.after(productDetailPageDTO.getSaleDateEnd()))){
			//不再销售期内，不允许预约
			logger.info("sale date is error !!");
			return false;
		}
		String projectCorpType = productDetailPageDTO.getCorpType();//产品发行类型
		if(Constants.FP_CORP_TYPE_PRIVATE.equals(projectCorpType)){//内销产品
			String corpId = loginUser.getManagerId();//登陆用户所属机构ID
			Integer productCorpId = productDetailPageDTO.getCorpId();//产品发行机构ID
			if(corpId.equals(productCorpId)){//
				return true;
			}else{
				logger.info("fa and corp is not !!");
				return false;
			}
		}else{
			return true;
		}
	}
	
	/**
	 * 判断登录人的操作权限
	 * @param request
	 * @param response
	 * @param faId 客户所属fa的ID（自由+机构fa）
	 * @throws Exception 
	 */
	private Boolean checkUserRight(HttpServletRequest request, HttpServletResponse response,String faId) throws Exception{
		Session session = SessionUtil.getSession();
		UserDTO loginUser = session.getUser();
		String type = loginUser.getUType();
		String userId = loginUser.getId();
		
		if(Constants.FA_TYPE_CORP.equals(type)){//登陆人为机构账户
			
			CorpFaUserDTO usreDTO = userService.getUserById(faId);//获取订单所属FA的基本信息
			
			List<Integer> intList =  orderService.getSonFaidList(userId);

			for(Integer i :intList){
				if(i.equals(usreDTO.getSource_code()) || faId.equals(userId)){
					return true;
				}
			}
			
			return false;
		}else{
			if(faId.equals(userId)){
				return true;
			}
			return false;
		}
		

	}
	
	/**
	 * 生成订单code
	 * @return
	 */
	private String createOrderCode(){
		logger.info("====>into orderCode create method<====");
		String orderCode = null;
		OrderVO queryVo = new  OrderVO();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		for(int i=0;i<5;i++){
			String currentTimeStr = sdf.format(new Date());
			String randomStr = RandomUtils.getRandomUtils(6);
			orderCode = currentTimeStr+randomStr;
			queryVo.setOrderCode(orderCode);
		}
		logger.info("====>orderCode create fail,please again!<====");
		return orderCode;
	}
	
	/**
	 * 对查询条件进行处理
	 * @param queryVo
	 * @return
	 */
	private OrderVO queryVoChange(OrderVO queryVo){
		Date appointmentDateEnd = queryVo.getAppointmentDateEnd();
		if(appointmentDateEnd!=null){
			Calendar c = Calendar.getInstance();
			c.setTime(appointmentDateEnd);
			c.add(Calendar.DAY_OF_MONTH, 1);
			queryVo.setAppointmentDateEnd(c.getTime());
		}
		return queryVo;
	}

	
	/**
	 * 消息和邮件发送
	 * @param params
	 */
//	private  void sendMessageAndMailTOWorker(Map<String,Object> params,String type,String code){
//		String otpMobile=PropertiesUtils.getValue("op_mobile");
//		String mailSender = PropertiesUtils.getValue("op_mail");
//		Map<String,Object> m  = MessageUtil.getMessage(type,code,params);
//		String title = (String)m.get(MessageUtil.KEY_TITLE);
//		String content = (String)m.get(MessageUtil.KEY_CONTENT);
//		//邮件发送
//		MessageMailDTO mail = new MessageMailDTO();
//		mail.setFpMailContent(content);
//		mail.setFpMailTitle(title);
//		mail.setFpMailTo(mailSender);
//		messageService.insertMailInfo(mail);
//		
//		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
//		messageSmsDTO.setFpSmsContent(content);
//		messageSmsDTO.setFpSmsRecivePhoneNo(otpMobile);
//		messageService.addMessageSms(messageSmsDTO);
//	}
	
	/**
	 * 申请预约
	 * @return
	 */
	@RequestMapping(value="/applyPreTmp/{pid}",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap applyWapPre(@PathVariable int pid,HttpServletRequest request, HttpServletResponse response,OrderDTO orderDto){
		ResultMap result = new ResultMap();
		try {
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			String oType = request.getParameter("oType");
			OrderTmpDTO dto = new OrderTmpDTO();
			ProductDetailPageDTO productDetailPageDTO = null;
			FpFundInfoDTO ffiDto = null;
			
			//机构不能预约产品
			String uType = loginUser.getUType();
			if(Constants.FA_TYPE_CORP.equals(uType)){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.ORDER_ORG_NOT_APPLY);
				result.setMessage("机构不能预约！");
				return result;
			}
			//02:私募产品预约
			if("02".equals(oType)){
				ffiDto =  fpFundInfoService.getFpFundInfo(Integer.valueOf(request.getParameter("productId")));
				dto.setProductId(Integer.valueOf(request.getParameter("productId")));

				if(ffiDto == null || StringUtil.isNullOrEmptyStr(ffiDto.getJjmc())){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
					result.setMessage("预约产品有误！");
					return result;
				}
				dto.setoClientMobile(request.getParameter("oClientMobile"));
				dto.setoClientName(request.getParameter("oClientName"));
				dto.setoRemark(request.getParameter("oRemark"));
				dto.setoAmount(new BigDecimal(request.getParameter("oAmount")));
			}else{
				productDetailPageDTO  = productService.getProductDetailView(pid);
			
				boolean check = checkProduct(request,response,productDetailPageDTO,loginUser);
				
				if(!check){
					result.setStatus(STATUS.FAILE);
					result.setStatusCode(ResultMap.ORDER_CODE_NOT_SALES_TIME);
					
					result.setMessage("预约产品有误！");
					return result;
				}
				dto.setProductId(pid);
			}
			
			
			dto.setFaId(faId);
			dto.setFaMobile(loginUser.getMobile());
			
			dto.setUpdateBy(loginUser.getLoginName());
			dto.setCreateBy(loginUser.getLoginName());
			dto.setoType(oType);
			dto.setUpdateDate(new Date());
			dto.setCreateDate(new Date());
			
			orderTmpServiceImpl.addOrderTmp(dto);
			
			Map<String,Object> params = new HashMap<String,Object>();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			params.put("uName", dto.getFaMobile());
			params.put("time", sdf.format(new Date()));
			params.put("productId", String.valueOf(dto.getProductId()));
			if(productDetailPageDTO != null){
				params.put("productShourName", productDetailPageDTO.getProductShortName());
			}else{
				params.put("productShourName", ffiDto.getJjmc());
			}
			
//			sendMessageAndMailTOWorker(params,"messageAndMail","wapOrderApplyPerWork");
			
			params.put("mailUrl", loginUser.getuEmail());
			params.put("otpMobile", loginUser.getLoginName());
			params.put("orderAmount",  Long.valueOf(dto.getoAmount().longValue()/10000).toString());
			params.put("orderNo", dto.getId().toString());
			sendMessageAndMailTOFA(params,"messageAndMail","wapOrderApplyPer",Constants.orderApplySmsAd);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			logger.error("==>error messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;		
	}
	/**
	 * 申请私募预约
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value="/applyPreTmpSM",method=RequestMethod.GET)
	@ResponseBody
	public ResultMap applyPreTmpSM(HttpServletRequest request, HttpServletResponse response,OrderDTO orderDto){
		ResultMap result = new ResultMap();
		try {
			
			//判断来源
			UserDTO loginUser = new UserDTO();
			if(StringUtils.isBlank(orderDto.getShopperId())){
				Session session = getSession(true);
				loginUser = session.getUser();
				orderDto.setShopperId(loginUser.getLoginName());
			}else{
				loginUser.setLoginName(orderDto.getShopperId());
				loginUser = userService.queryUserLoginName(loginUser);
			}
			
			String validatecode = request.getParameter("validatecode");
			String mobile = request.getParameter("mobile");
			String loginName= loginUser.getLoginName();
			
			//检查数据是否为空
			if(StringUtils.isBlank(validatecode) && StringUtils.isBlank(orderDto.getShopperId())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setMessage("参数缺失");
				return result;
			}
			//判断店铺产品上下架
//			FpShopperProductDTO shop=new FpShopperProductDTO();
//			shop.setProductState(1);  //默认为上架的
//			shop.setProductId(orderDto.getPid()+"");
//			shop.setUserId(loginUser.getId()); 
//			List<ShopperProductVO> queryShopperProduct = fpShopperProductService.queryShopperProduct(shop,null);
//			if(queryShopperProduct.size()==0){
//				result.setStatus(STATUS.FAILE);
//				result.setStatusCode(ResultMap.PRODUCT_DOWN);
//				result.setMessage("产品已下架");
//				return result;
//			}
			
			if(!StringUtils.isBlank(validatecode)){
				//手机验证码
				if(checkCodeServiceImpl.CheckCodeSwitch()){
					Integer activety_otp_time= new Integer(PropertiesUtils.getValue("activety_otp_time"));
					//验证码超时
					if(checkOtpCodeTimeOut(mobile,activety_otp_time,ISmsService.OTP_CODE_FIRST_TIME)){
						result.setStatus(ResultMap.STATUS.FAILE);
						result.setStatusCode(ResultMap.STATUS_CODE_OTP_VALIDATE_ERROR_TIMEOUT);
						result.setMessage("手机验证码超时！");
						return result;
						
					};
					ResultMap resultOtp = checkOtpCode(mobile,validatecode);
					if(!STATUS.SUCCESS.equals(resultOtp.getStatus())){
						result.setStatus(resultOtp.getStatus());
						result.setStatusCode(resultOtp.getStatusCode());
						result.setMessage(resultOtp.getMessage());
						return result;
					}
				}
			}
			
			
			String faId = loginUser.getId();
			OrderTmpDTO dto = new OrderTmpDTO();
			ProductDetailPageDTO productDetailPageDTO = null;
			FpFundInfoDTO ffiDto = null;
			
			
			ffiDto =  fpFundInfoService.getFpFundInfo(Integer.valueOf(request.getParameter("productId")));
			dto.setProductId(Integer.valueOf(request.getParameter("productId")));
			if(ffiDto == null || StringUtil.isNullOrEmptyStr(ffiDto.getJjmc())){
				result.setStatus(STATUS.FAILE);
				result.setStatusCode(ResultMap.STATUS_CODE_OBJECT_NOFOUNT);
				result.setMessage("预约产品有误！");
				return result;
			}
			// 更改手机号从登录中取 by 【有单】
//			dto.setoClientMobile(request.getParameter("oClientMobile"));
			dto.setoClientMobile(loginUser.getMobile());
			dto.setoClientName(request.getParameter("oClientName"));
			dto.setoRemark(request.getParameter("oRemark"));
			dto.setoAmount(new BigDecimal(request.getParameter("oAmount")));
			dto.setFaId(faId);
			dto.setFaMobile(loginUser.getMobile());
			
			dto.setUpdateBy(loginUser.getLoginName());
			dto.setCreateBy(loginUser.getLoginName());
			dto.setoType("02");
			dto.setUpdateDate(new Date());
			dto.setCreateDate(new Date());
			
			orderTmpServiceImpl.addOrderTmp(dto);
			
			Map<String,Object> params = new HashMap<String,Object>();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			params.put("uName", dto.getFaMobile());
			params.put("time", sdf.format(new Date()));
			params.put("productId", String.valueOf(dto.getProductId()));
			params.put("orderAmount", dto.getoAmount().toString());
			params.put("otpMobile", loginUser.getLoginName());
			params.put("shopperId", orderDto.getShopperId());
			
			if(productDetailPageDTO != null){
				params.put("productShourName", productDetailPageDTO.getProductShortName());
			}else{
				params.put("productShourName", ffiDto.getJjmc());
			}
				
			sendMessageAndMailTOFA(params,"messageAndMail","applyOrderWorkShop",Constants.ClientOrderSendSms);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("==>error messang:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;		
	}
	/**
	 * 排序方式，将参数转化成数据库参数
	 * @param OrderType
	 * @return
	 */
	private void  getOrderOrderType(OrderVO orderVo){
		if(StringUtil.isNullOrEmptyStr(orderVo.getOrderParameter())){
			orderVo.setOrderParameter(null);
			return;
		}
		//01 预约时间 02 产品名称 03认购金额 04交易状态
 		if("01".equals(orderVo.getOrderParameter())){
 			orderVo.setOrderParameter("o.CREATE_DATE");
 		}else if("02".equals(orderVo.getOrderParameter())){
 			orderVo.setOrderParameter("p.p_name");
 		}else if("03".equals(orderVo.getOrderParameter())){
 			orderVo.setOrderParameter("o.O_AMOUNT");
 		}else if("04".equals(orderVo.getOrderParameter())){
 			orderVo.setOrderParameter("o.O_STATUS");
 		}else{
 			orderVo.setOrderParameter(null);
 		}
 		//01 降序 02 升序
 		if("01".equals(orderVo.getOrderType())){
 			orderVo.setOrderType("desc");
 		}else if("02".equals(orderVo.getOrderType())){
 			orderVo.setOrderType("asc");
 		}else{
 			orderVo.setOrderType("desc");
 		}
		
	}
	
	@RequestMapping("/applyTopList")
	@ResponseBody
	public ResultMap applyTopList(String limit){
		ResultMap result = new ResultMap();
		
		log.info("begin applyList !");
		
		List<Map<String,Object>> orderList = new ArrayList<Map<String,Object>>();
		Integer limits = 5;
		try {
			try{
				limits = Integer.valueOf(limit);
			}catch(Exception e){
				log.warn("format num error!",e);
			}
			if(limits > 20 || limits <= 0){
				limits = 5;
			}
			
			List<OrderDTO> orderVoList  = orderService.queryTOPOrder(limits);
			for(OrderDTO order:orderVoList){
				Map<String,Object> resultTmpMap = new HashMap<String,Object>();
				String faName = order.getFaName();
				
				if(faName != null){
					order.setFaName(faName.replace(faName.substring(1), "****"));
				}
			
				resultTmpMap.put("order", order);
				resultTmpMap.put("project", productService.getProductDetailView(order.getPid()));
				orderList.add(resultTmpMap);
			}
			result.setAttribute("list", orderList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e){
			logger.error("apply list query error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 展示所有出单订单列表
	 * @return
	 */
	@RequestMapping("/myList")
	@ResponseBody
	public ResultMap myList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		BigDecimal allRebateAmount = new BigDecimal(-1);
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			orderVo.setFaid(faId);
			Pager pager = new Pager();
			Integer count = orderService.getOrderListCount(orderVo);
			pager.setTotalCount(count); 
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());
			
			//排序方式，将参数转化成数据库参数
			getOrderOrderType(orderVo);
			
			List<OrderDTO> orderDtoList = orderService.getOrderList(orderVo);
			
			if(orderDtoList!=null&&orderDtoList.size()>0){
				for (int i = 0; i < orderDtoList.size(); i++) {
					try {
						if(DateUtil.format(oldOrderTime, "yyyy-MM-dd").before(orderDtoList.get(i).getCreateDate())){
							orderDtoList.get(i).setFlagUpload(true);
						}else{
							orderDtoList.get(i).setFlagUpload(false);
						}
					} catch (Exception e) {
						orderDtoList.get(i).setFlagUpload(false);
						log.error("format oldOrderTime",e);
					}
					
					FpOrderPhoDTO fpd=new FpOrderPhoDTO();
					fpd.setoId(orderDtoList.get(i).getId());
					List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);
					
					//默认状态为未提交审核
					String phoStatus = Constants.order_data_pho_rev_no;
					Map<String,String> map = new HashMap<String,String>();
					for(FpOrderPhoDTO PODtmp  : PODList){
						
						if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
							map.put("01", "01");
							continue;
						}
						map.put(PODtmp.getoPhoStatus(), "01");
					}
					
				}
			}
			// 已经结佣总金额 前端、后端佣金
			allRebateAmount = orderService.getMyOrderAllRebateAmount(orderVo);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", orderDtoList);
			result.setAttribute("pager", pager);
			result.setAttribute("rebateAmount", allRebateAmount);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 展示所有出单订单列表
	 * @return
	 */
	@RequestMapping("/myCommissionList")
	@ResponseBody
	public ResultMap myCommissionList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){

		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			orderVo.setFaid(faId);
			Pager pager = new Pager();

			orderVo.setPayStatusStage("Y");
			orderVo.setPayStatusStageStart("330");
			orderVo.setPayStatusStageEnd("360");
			Integer count = orderService.getOrderListCount(orderVo);
			pager.setTotalCount(count);
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());

			//排序方式，将参数转化成数据库参数
			getOrderOrderType(orderVo);




			List<OrderDTO> orderDtoList = orderService.getOrderList(orderVo);

			for (OrderDTO bean :orderDtoList){
				bean.setCreateDateStr(DateUtil.formatDate(bean.getCreateDate(),"yyyy/MM/dd"));
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", orderDtoList);
			result.setAttribute("pager", pager);

		} catch (Exception e) {
			logger.error(":myCommissionList  is error:",e);
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 展示所有收单订单列表 产品维度
	 * @return
	 */
	@RequestMapping("/myBiddingProjectList")
	@ResponseBody
	public ResultMap myBiddingProjectList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		Map<String, Object> tempMap = new HashMap<String, Object>();
		BigDecimal allRebateAmount = new BigDecimal(0);
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			orderVo.setFaid(faId);
			Pager pager = new Pager();
			// 查询出收单相关产品条数
			Integer count = orderService.getBiddingProjectListCount(orderVo);
			pager.setTotalCount(count);
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());
			List<YouDanOrderByProjectDTO> resultList = new ArrayList<YouDanOrderByProjectDTO>();
			YouDanOrderByProjectDTO youDanAmount = new YouDanOrderByProjectDTO();
			if(null != count && count > 0){
				// 查询出收单相关产品
				List<YouDanOrderByProjectDTO> orderDtoList = orderService.getBiddingProjectList(orderVo);
				// 查询产品维度的订单金额信息
				for (YouDanOrderByProjectDTO productDTO : orderDtoList) {
					tempMap.put("pid", productDTO.getId());
					tempMap.put("biddingReceiptId", productDTO.getBiddingReceiptId());
					tempMap.put("oOwnerId", faId);
					tempMap.put("pName", productDTO.getName());
					tempMap.put("biddingStatus", productDTO.getBiddingStatus());
					tempMap.put("pCode", productDTO.getCode());
					//查询金额相关
					youDanAmount = orderService.getYouDanOrderByProject(tempMap);
					productDTO.setReservedAmount(youDanAmount.getReservedAmount());
					productDTO.setConfirmedAmount(youDanAmount.getConfirmedAmount());
					productDTO.setPayingCommission(youDanAmount.getPayingCommission());
					productDTO.setPayedCommission(youDanAmount.getPayedCommission());
					resultList.add(productDTO);
				}
				// 查询收单已付佣金总额
				allRebateAmount = orderService.getMyYouDanOrderAllRebateAmount(orderVo);
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", resultList);
			result.setAttribute("pager", pager);
			result.setAttribute("rebateAmount", allRebateAmount);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 收单订单-产品维度详情页-4个金额 包含佣金范围
	 * @return
	 */
	@RequestMapping("/myBiddingProjectAmount")
	@ResponseBody
	public ResultMap myBiddingProjectAmount(HttpServletRequest request, HttpServletResponse response){ 
		ResultMap result = new ResultMap();
		try {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			// 查询金额相关
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			tempMap.put("oOwnerId", faId);
			tempMap.put("pid", request.getParameter("pid"));
			tempMap.put("biddingReceiptId", request.getParameter("receiptId"));
			YouDanOrderByProjectDTO dto = orderService.myBiddingProjectAmount(tempMap);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", dto);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 收单订单-产品维度详情页-指定产品下订单列表
	 * @return
	 */
	@RequestMapping("/myBiddingOrderList")
	@ResponseBody
	public ResultMap myBiddingOrderList(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		String pageNo = request.getParameter("pageNo");
		if(StringUtils.isBlank(pageNo)){
			pageNo="1";
		}
		try {
			orderVo.setFaid(faId);
			Pager pager = new Pager();
			// 查询出该产品的订单数
			Integer count = orderService.getYouDanOrderListCount(orderVo);
			pager.setTotalCount(count);
			pager.setPageSize(orderVo.getPageSize());
			pager.setPageNo(Integer.parseInt(pageNo));
			orderVo.setStart(pager.getStartIndex());
			List<OrderDTO> orderDtoList = new ArrayList<OrderDTO>();;
			// 查询出收单相关产品条数
			if(count != 0){
				orderDtoList = orderService.getYouDanOrderList(orderVo);
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("list", orderDtoList);
			result.setAttribute("pager", pager);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 收单订单-产品维度详情页-订单详情页
	 * @return
	 */
	@RequestMapping("/myBiddingOrderDetail")
	@ResponseBody
	public ResultMap myBiddingOrderDetail(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		try {
			orderVo.setFaid(faId);
			OrderDTO orderDto = orderService.getYouDanOrderDetail(orderVo);
			// 上传资料相关
			FpOrderPhoDTO fpd = new FpOrderPhoDTO();
			fpd.setoId(orderVo.getId());
			List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);
			
			//默认状态为未提交审核
			String phoStatus = Constants.order_data_pho_rev_no;
			Map<String,String> map = new HashMap<String,String>();
			for(FpOrderPhoDTO PODtmp  : PODList){
				
				if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
					map.put("01", "01");
					continue;
				}
				map.put(PODtmp.getoPhoStatus(), "01");
				
			}
			
			if(map.containsKey(Constants.order_data_pho_rev_no)){
				
				 phoStatus = Constants.order_data_pho_rev_no;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_fail)){
				
				 phoStatus = Constants.order_data_pho_rev_fail;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_yes)){
				
				 phoStatus = Constants.order_data_pho_rev_yes;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
				
				 phoStatus = Constants.order_data_pho_rev_success;
				 result.setAttribute("PODList", PODList);
			}
			
			result.setAttribute("phoStatus", phoStatus);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", orderDto);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 *  出单订单-产品维度详情页-订单详情页
	 * @return
	 */
	@RequestMapping("/myOrderDetail")
	@ResponseBody
	public ResultMap myOrderDetail(HttpServletRequest request, HttpServletResponse response,OrderVO orderVo){ 
		ResultMap result = new ResultMap();
		Session session = getSession(true);
		UserDTO loginUser = session.getUser();
		String faId = loginUser.getId();
		OrderDTO orderDTO = new OrderDTO();
		try {
			orderVo.setFaid(faId);
			//排序方式，将参数转化成数据库参数
			getOrderOrderType(orderVo);
			
			List<OrderDTO> orderDtoList = orderService.getOrderList(orderVo);
			
			if(orderDtoList!=null&&orderDtoList.size() == 1){
				orderDTO = orderDtoList.get(0);
				try {
					if(DateUtil.format(oldOrderTime, "yyyy-MM-dd").before(orderDTO.getCreateDate())){
						orderDTO.setFlagUpload(true);
					}else{
						orderDTO.setFlagUpload(false);
					}
				} catch (Exception e) {
					orderDTO.setFlagUpload(false);
					log.error("format oldOrderTime",e);
				}
				
				FpOrderPhoDTO fpd=new FpOrderPhoDTO();
				fpd.setoId(orderDTO.getId());
				List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);
				
				//默认状态为未提交审核
				String phoStatus = Constants.order_data_pho_rev_no;
				Map<String,String> map = new HashMap<String,String>();
				for(FpOrderPhoDTO PODtmp  : PODList){
					
					if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
						map.put("01", "01");
						continue;
					}
					map.put(PODtmp.getoPhoStatus(), "01");
				}
				
				if(map.containsKey(Constants.order_data_pho_rev_no)){
					 phoStatus = Constants.order_data_pho_rev_no;
					 orderDTO.setDataStatus(phoStatus);
				}else if(map.containsKey(Constants.order_data_pho_rev_fail)){
					 phoStatus = Constants.order_data_pho_rev_fail;
					 orderDTO.setDataStatus(phoStatus);
				}else if(map.containsKey(Constants.order_data_pho_rev_yes) ){
					 phoStatus = Constants.order_data_pho_rev_yes;
					 orderDTO.setDataStatus(phoStatus);
				}else if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
					 phoStatus = Constants.order_data_pho_rev_success;
					 orderDTO.setDataStatus(phoStatus);
				}
			}
			// 上传资料相关
			FpOrderPhoDTO fpd = new FpOrderPhoDTO();
			fpd.setoId(orderVo.getId());
			List<FpOrderPhoDTO> PODList=productOrderDataService.findProductOrderPhos(fpd);
			
			//默认状态为未提交审核
			String phoStatus = Constants.order_data_pho_rev_no;
			Map<String,String> map = new HashMap<String,String>();
			for(FpOrderPhoDTO PODtmp  : PODList){
				
				if(StringUtils.isBlank(PODtmp.getoPhoStatus())){
					map.put("01", "01");
					continue;
				}
				map.put(PODtmp.getoPhoStatus(), "01");
				
			}
			
			if(map.containsKey(Constants.order_data_pho_rev_no)){
				
				 phoStatus = Constants.order_data_pho_rev_no;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_fail)){
				
				 phoStatus = Constants.order_data_pho_rev_fail;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_yes)){
				
				 phoStatus = Constants.order_data_pho_rev_yes;
			}else
			if(map.containsKey(Constants.order_data_pho_rev_success) && !map.containsKey(Constants.order_data_pho_rev_yes)){
				
				 phoStatus = Constants.order_data_pho_rev_success;
			}
			// add 预约中、预约失败情况
		
			
			result.setAttribute("phoStatus", phoStatus);
			result.setAttribute("PODList", PODList);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", orderDTO);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
	/**
	 * 收单订单-产品维度详情页-具体佣金
	 * @return
	 */
	@RequestMapping("/myBiddingProjectCommission")
	@ResponseBody
	public ResultMap myBiddingProjectCommission(HttpServletRequest request, HttpServletResponse response){ 
		ResultMap result = new ResultMap();
		try {
			Map<String, Object> tempMap = new HashMap<String, Object>();
			// 查询金额相关
			Session session = getSession(true);
			UserDTO loginUser = session.getUser();
			String faId = loginUser.getId();
			tempMap.put("ownerId", faId);
			tempMap.put("pid", request.getParameter("pid"));
			tempMap.put("receiptId", request.getParameter("receiptId"));
			List<YouDanCommissionDTO> resultList = orderService.myBiddingProjectCommission(tempMap);
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("result", resultList);
		} catch (Exception e) {
			logger.warn("==>warn messang:"+e.getMessage());
			result.setStatus(STATUS.WARN);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return  result;
	}
}
